package ui

import (
	"errors"
	"image/color"
	"log"
	"regexp"
	"strconv"
	"time"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/widget"
)

func updateTime(clock *widget.Label) {
	formatted := time.Now().Format("现在的时间是: 2006-01-02 15:04:05")
	clock.SetText(formatted)
}

func TimeUi(w fyne.Window) (c *fyne.Container) {

	nowTimeText := widget.NewLabel("")
	formatted := time.Now().Format("现在的时间是: 2006-01-02 15:04:05")
	nowTimeText.SetText(formatted)

	go func() {
		for range time.Tick(time.Second) {
			updateTime(nowTimeText)
		}
	}()

	t1 := canvas.NewText("Unix时间戳（Unix timestamp）", color.White)
	t1.TextSize = 10
	t2 := widget.NewEntry()
	t2.Resize(fyne.NewSize(100, 25))
	t2.MultiLine = false
	t2.PlaceHolder = "10位的数字时间戳"
	t3 := canvas.NewText("秒", color.White)
	t5 := widget.NewLabel("")
	t4 := widget.NewButton("转换", func() {
		if len(t2.Text) != 10 {
			dialog.NewError(errors.New("时间戳是10位的数字"), w).Show()
			return
		}
		log.Println("input 内容:", t2.Text)
		i, err := strconv.Atoi(t2.Text)
		if err != nil {
			dialog.NewError(err, w).Show()
			return
		}
		unixStr := time.Unix(int64(i), 0).Format("2006-01-02 15:04:05")
		t5.SetText(unixStr)
	})

	content := container.New(layout.NewGridLayoutWithColumns(3), t1, t2, t3, layout.NewSpacer(), t4, t5)

	l1 := canvas.NewText("时间字符串（年-月-日 时:分:秒）", color.White)
	l1.TextSize = 10
	l2 := widget.NewEntry()
	l2.MultiLine = false
	l4 := widget.NewLabel("")
	l3 := widget.NewButton("转换成Uinx时间戳", func() {
		str := "^[1-9][0-9]{3}-[0|1][1-9]-[0|1|2|3][0-9] [0|1|2][1-9]:[0-5][0-9]:[0-5][0-9]$"
		r, err := regexp.Compile(str)
		log.Println("输入内容：", l2.Text, r)
		if err != nil {
			dialog.NewError(err, w).Show()
			return
		}
		b := r.MatchString(l2.Text)
		if !b {
			dialog.NewError(errors.New("格式不正确"), w).Show()
			return
		}
		t, err := time.Parse("2006-01-02 15:04:05", l2.Text)
		if err != nil {
			dialog.NewError(err, w).Show()
			return
		}
		l4.SetText(strconv.FormatInt(t.UTC().Unix(), 10))
	})
	l5 := canvas.NewText("秒", color.White)
	c2 := container.New(layout.NewGridLayoutWithColumns(3), l1, l2, l3, layout.NewSpacer(), l4, l5)

	c = container.New(layout.NewVBoxLayout(), nowTimeText, content, c2)
	return
}
